import axios from 'axios'
import router from "@/router"
import { message } from 'antd'

const axiosInstance = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  timeout: 5000,
  withCredentials: true
})
const apiList = ['/users/login']
axiosInstance.interceptors.request.use(
  (config: any) => {
    if(!apiList.includes(config.url)){
      const token = sessionStorage.getItem("token") || ''
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  (response: any) => {
    const { code, message:msg } = response.data
    if(code !== 200){
      const { code } = response.data
      switch(code){
        //token过期
        case 10006:
        case 10007:
          router.navigate("/login",{
            replace:true
          })
          break
        default:
          break
      }
      return Promise.reject(msg).catch(e=>{
        message.error(msg)
      })
    }
    if(response.data && response.data.token){
      // 登录成功加token
      sessionStorage.setItem("token",response.data.token)
    }
    return Promise.resolve(response)
  },
  (error: any) => {
    return Promise.reject(error)
  }
)
export default axiosInstance
